<template>
  <div>

    <!--    <el-upload
          class="upload-demo"
          :action="uploadInfo.host?uploadInfo.host:'#'"
          :data="uploadInfo"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          list-type="picture">
          <el-button size="small" type="primary">点击上传</el-button>
          <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
        </el-upload>-->

    <!--    上传的时候不能添加name属性，否则无法上传 400 错误
                  :name="fileName"
    -->
    <!--    <img  alt="" class="el-upload-list__item-actions">-->

    <el-upload
      class="upload-demo"
      :action="uploadInfo.host?uploadInfo.host:'#'"
      :data="uploadInfo"
      :on-preview="handlePictureCardPreview"
      :on-remove="handleRemove"
      :before-remove="beforeRemove"
      :before-upload="beforeUpload"
      :on-success="uploadSuccess"
      :file-list="fileList"
      :multiple="false"
      ref="elUpload"
      list-type="picture">
      <el-button size="small" type="primary">点击上传</el-button>
      <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
    </el-upload>
    <!-- <el-upload
          :action="uploadInfo.host?uploadInfo.host:'#'"
          :data="uploadInfo"
          list-type="picture-card"
          :multiple="false"
          :before-upload="beforeUpload"
          :on-success="uploadSuccess"
          :before-remove="beforeRemove"
          ref="uploadFile"
          :auto-upload="true">

          <i slot="default" class="el-icon-plus"></i>

          <template slot="file" slot-scope="file">

            <img
              class="el-upload-list__item-thumbnail"
              :src.sync="uploadInfo.host+'/'+fileNameAndPath" alt="">

            <span class="el-upload-list__item-actions">

              <span
                class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)">

                <i class="el-icon-zoom-in"></i>
              </span>

              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleDownload(file)">
                <i class="el-icon-download"></i>
              </span>

              <span
                v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)">
                <i class="el-icon-delete"></i>
              </span>

            </span>
          </template>
        </el-upload>
    -->

    <el-dialog :visible.sync="dialogVisible">
      <img width="100%" v-if="fileList.length>0" :src="fileList[0].url" alt="">
    </el-dialog>

  </div>


</template>

<script>
import uploadToAiliOss from '../../api/uploadToAiliOss'
import {getUUID} from '../../utils'

export default {
  props: ['fileUrl', 'fileListUrl'],
  data () {
    return {
      dialogImageUrl: '',
      dialogVisible: false,
      disabled: false,
      uploadInfo: {},
      updatePolicyTimer: 0,
      //fileNameAndPath: null,
      fileList: [],
      hostAddress: null
      /*fileList: [
        {name: '', url: ''}
      ]*/
    }
  },
  methods: {
    handleRemove (file, fileList) {
      //console.log('删除文件', file)

      this.$emit('update-file-list', fileList, file)
    },

    clearFileNameAndPath () {
      console.log('子组件的图片路径已经被父组件清空')
      //this.fileNameAndPath = null
    },

    beforeRemove (file, fileList) {

      this.$emit('update-file', '')
      //this.$emit('delete-logo', this.uploadInfo.key)
      /*      uploadToAiliOss.deleteFileOfDbAndOss(this.uploadInfo.key,this.uploadInfo.key).then(() => {

              this.$message({
                message: `logo:${file.name}删除成功`,
                type: 'success'
              })
              //this.fileNameAndPath = null
            })*/
    },

    handlePictureCardPreview (file) {
      //this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handleDownload (file) {
      console.log(file)
    },
    getUploadPolicy () {
      uploadToAiliOss.getUploadingFilePolicy().then(({data}) => {
        this.uploadInfo = data
        //this.actionAddress = data.host;

        //this.uploadInfo.policy = data.policy;
        //this.uploadInfo.signature = data.signature;
        //this.uploadInfo.OSSAccessKeyId = data.OSSAccessKeyId;
        //this.uploadInfo.key = data.dir + '/'+getUUID()+'_${filename}';
        //this.uploadInfo.dir = data.dir;
        //this.uploadInfo.host = data.host;

        this.uploadInfo['success_action_status'] = 200 //让服务端返回200,不然，默认会返回204

        /**
         * policy快要到期的时候更新policy
         * */
          // 可以判断当前expire是否超过了当前时间， 如果超过了当前时间， 就重新取一下，3s 作为缓冲。
        let now = Date.parse(new Date()) / 1000

        //console.log('上传组件', this.uploadInfo, `${data.expire - now - 3}秒后要重新获取policy`)

        this.updatePolicyTimer = setTimeout(() => {

          this.getUploadPolicy()

        }, (data.expire - now - 3) * 1000)
      })
    },
    beforeUpload (file) {
      this.uploadInfo.key = this.uploadInfo.dir + `/${getUUID()}-${file.name}`
      // this.fileNameAndPath = this.uploadInfo.key
      console.log('上传之前设置的文件名是', this.uploadInfo.key)

      /**
       * 把上传后的key放入file中，之后可以通过fileList中查看
       * */
      file.key = this.uploadInfo.key

    },
    uploadSuccess (response, file, fileList) {
      this.$message({
        type: 'success',
        message: `品牌logo:${file.name}上传成功`
      })
      console.log('上传成功', response, file,'fileList = ', fileList);
      this.$emit('update-file', file.raw.key);
      this.$emit('update-file-list', fileList);
    },
    async getHostAddress () {
      let p = await uploadToAiliOss.getHostAddress()
      this.hostAddress = p.data.host + '/'
    }

  },
  created () {
    this.getUploadPolicy()
    this.getHostAddress()
  },
  mounted () {
    //this.$refs.elUpload.clearFiles();

  },
  watch: {
    /*fileNameAndPath (val) {
      console.log('子组件中的updateFileNameAndPath更新了', val)
      this.$emit('update-file', val)
    },*/

    /**
     * 这个监听器永远也不会触发
     * */
    'uploadInfo.key' (val) {
      console.log('上传子组件中的uploadInfo.key更新了', val)
      this.$emit('update-file', val)
    },
    /**
     * 监听显示单个文件
     * */
    fileUrl (val) {
      console.log('上传组件监听到文件地址的变化', val)

      //this.$refs.elUpload.clearFiles();
      //this.fileNameAndPath = val
      this.fileList = []

        uploadToAiliOss.getHostAddress().then(({data}) => {

          //this.fileList.splice(0, this.fileList.length)

          /*this.fileList[0].url = data.host + '/' + val
          this.fileList[0].name = val.substring(val.lastIndexOf('-') + 1)*/

          //console.log('更新之后的fileList是', this.fileList)

          this.uploadInfo.key = val

          this.fileList.push({
            name: val.substring(val.lastIndexOf('-') + 1),
            url: data.host + '/' + val
          })
        })


    },

    /**
     * 监听显示多个文件
     * ['http://sdf','http://sdfswe.jpg']
     * */
    fileListUrl (val) {


        // console.log('图片上传组件接收到多张图片', val)
        if(val&&val.length>0) {
          this.fileList = []

          val.forEach(img => {
            if (img != null) {
              this.fileList.push({
                name: img.substring(img.lastIndexOf('-') + 1),
                url: img.startsWith('20') ? this.hostAddress + img : img
              })
            }

          })
        }

    }
  },
}
</script>

<style scoped>

</style>
